<template>
	<div>
		<div class="container">
			<div class="toolbar">
				<a-form ref="searchRef" :model="searchState" @finish="current=1;loading=true;initData()">
					<!--					<a-form-item label="选择项目" style="width:250px">-->
					<!--						<a-select v-model:value="searchState.project_id" :show-search="true" placeholder="请选择项目" :options="projectlist" option-filter-prop="label"></a-select>-->
					<!--					</a-form-item>-->
					<a-row :gutter="20">
						<a-col :span="24">
							<a-form-item label="选择类型">
								<a-radio-group v-model:value="searchState.type" @change="doSearch">
									<a-radio-button v-for="option of typeOptions" :key="option.value" :value="option.value">{{ option.label }}</a-radio-button>
								</a-radio-group>
							</a-form-item>
						</a-col>
					</a-row>
					<a-row v-if="searchState.type === 0" :gutter="20">
						<a-col :span="8">
							<a-form-item label="城市公司/专业公司">
								<a-select v-model:value="searchState.company_id" :show-search="true" placeholder="请选择城市公司/专业公司" :options="companyOptions" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="选择项目">
								<a-select v-model:value="searchState.project_id" :show-search="true" placeholder="请选择项目" :options="innerProjectOptions" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="接收人" name="receiver_name">
								<a-input v-model:value="searchState.receiver_name" placeholder="请输入接收人" allow-clear></a-input>
							</a-form-item>
						</a-col>
					</a-row>
					<a-row v-if="searchState.type === 1" :gutter="20">
						<a-col :span="8">
							<a-form-item label="选择项目">
								<a-select v-model:value="searchState.project_id" :show-search="true" placeholder="请选择项目" :options="innerProjectOptions" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="物资名称" name="material_name">
								<a-input v-model:value="searchState.material_name" placeholder="请输入物资名称" allow-clear></a-input>
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="20">
						<a-col :span="12">
							<a-form-item label="时间范围">
								<a-range-picker v-model:value="searchState.date_range" format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item>
								<a-space>
									<a-button type="primary" html-type="submit">
										<search-outlined />搜索
									</a-button>
									<a-button type="primary" @click="handleExport">
										<export-outlined />导出
									</a-button>
									<!-- <a-button @click="router.push('uselog/create')">
										<plus-outlined />添加
									</a-button> -->
								</a-space>
							</a-form-item>
						</a-col>
					</a-row>
				</a-form>
			</div>

			<div class="mt-2">
				<!--
				v-if="!loading"使得:default-expand-all-rows="true"生效
				-->
				<a-table v-if="!loading" :columns="columns" :scroll="tableScroll" row-key="id" children-column-name="children" :default-expand-all-rows="false" :data-source="acceptSource" :pagination="pagination" :loading="loading" @change="initData">
					<template #bodyCell="{ column, record }">
						<template v-if="column.key === 'operation'">
							<a-space>
								<a-button v-permission="75" type="link" @click="showUselog(record)">
									<right-outlined />查看
								</a-button>
								<!--
								<a-button type="link" @click="editUselog(record)">
									<edit-outlined />修改
								</a-button>
								<a-button type="link" style="color:#ff7875" @click="deleteUselog(record.id)">
									<delete-outlined />删除
								</a-button>
								-->
							</a-space>
						</template>
						<template v-else-if="column.key === 'flowStatus'">
							<div>
								<flow-model :module-id="'planjx'" :item-id="record.id" @change="changeFlowStatusData2"></flow-model>
							</div>
						</template>
					</template>
				</a-table>
			</div>
		</div>
	</div>
</template>

<script setup>
import { reactive, ref, computed, getCurrentInstance } from "vue";
import { useRoute, useRouter } from "vue-router";
const companyOptions = ref([]);
const projectOptions = ref([]);
const { proxy } = getCurrentInstance();
import dayjs from "dayjs";

import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, RightOutlined, ExportOutlined } from "@ant-design/icons-vue";

import { post } from "../utils";

import { usePagination } from "vue-request";

const route = useRoute();
const router = useRouter();
const query = route.query;
const searchRef = ref();
const searchState = reactive({
	type: 0,
});
const typeOptions = [
	{
		value: 0,
		label: "项目统计"
	},
	{
		value: 1,
		label: "物资统计"
	},
];
const getProjects = async () => {
	const projectResult = await post("department/projects", { type: 3, get_type: 1, is_effective: true });
	projectOptions.value = projectResult.data.map(d => {
		return {
			value: d.id,
			label: d.name,
			parseIds: d.parent_ids.split(',').map(item => parseInt(item)),
		};
	});
}
if (!projectOptions.value.length) {
	getProjects();
}
post("department/projects?type=2", {
	parent_ids: JSON.stringify([78, 24]),
}).then(({ data }) => {
	companyOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.name,
			parseIds: d.parent_ids.split(',').map(item => parseInt(item)),
		};
	});
});
const columns = computed(() => {
	if (searchState.type === 0) {
		return [
			{
				title: "ID",
				dataIndex: "id",
				key: "id",
				width: 80,
				align: "left",
				fixed: "left"
			},
			{
				title: "项目名称",
				fixed: "left",
				dataIndex: "project",
				sorter: false,
				width: 200,
				ellipsis: true,
				customRender: ({ text, record, index, column }) => {
					//未设置dataIndex，text和record返回值相同
					return text.name;
				}
			},
			{
				title: "工号",
				dataIndex: "gonghao",
				sorter: false,
				width: 150,
				ellipsis: true,
				customRender: ({ text, record, index, column }) => {
					//未设置dataIndex，text和record返回值相同
					return text?.name;
				}
			},
			{
				title: "发料人",
				dataIndex: "user",
				sorter: false,
				width: 150,
				align: "center",
				customRender: ({ text, record, index, column }) => {
					//未设置dataIndex，text和record返回值相同
					return text.fullname;
				}
			},
			{
				title: "物料接收人",
				dataIndex: "receiver",
				sorter: false,
				width: 240,
				align: "center",
				ellipsis: true
			},
			{
				title: "发料日期",
				dataIndex: "create_time",
				sorter: false,
				width: 150,
				align: "center",
				customRender: ({ text, record, index, column }) => {
					//未设置dataIndex，text和record返回值相同
					return dayjs(text).format("YYYY-MM-DD HH:mm:ss");
				}
			},
			{
				title: "签收状态",
				dataIndex: "receive_status",
				sorter: false,
				width: 100,
				align: "center",
				customRender: ({ text, record, index, column }) => {
					return text === 1 ? "待收料" : "已收料";
				}
			},
			{
				title: "操作",
				key: "operation",
				sorter: false,
				fixed: "right",
				width: 80,
				align: "center"
			}
		];
	} else {
		return [
			{
				title: "ID",
				dataIndex: "id",
				key: "id",
				width: 80,
				align: "left",
				fixed: "left"
			},
			{
				title: "项目名称",
				fixed: "left",
				dataIndex: "project",
				sorter: false,
				width: 200,
				ellipsis: true,
				customRender: ({ text, record, index, column }) => {
					//未设置dataIndex，text和record返回值相同
					return text.name;
				}
			},
			{
				title: "物料名称",
				dataIndex: "material",
				sorter: false,
				width: 200,
				ellipsis: true,
				customRender: ({ text, record, index, column }) => {
					return text.name;
				}
			},
			{
				title: "物料规格",
				dataIndex: "material",
				sorter: false,
				width: 200,
				ellipsis: true,
				customRender: ({ text, record, index, column }) => {
					return text.model;
				}
			},
			{
				title: "单位",
				dataIndex: "material",
				sorter: false,
				width: 200,
				ellipsis: true,
				customRender: ({ text, record, index, column }) => {
					return text.unit;
				}
			},
			{
				title: "库存数量",
				dataIndex: "material",
				sorter: false,
				width: 200,
				ellipsis: true,
				customRender: ({ text, record, index, column }) => {
					return text.UselogMaterial?.quantity;
				}
			},
			{
				title: "发料数量",
				dataIndex: "material",
				sorter: false,
				width: 200,
				ellipsis: true,
				customRender: ({ text, record, index, column }) => {
					return text.UselogMaterial?.send_qty;
				}
			},
			{
				title: "发料日期",
				dataIndex: "create_time",
				sorter: false,
				width: 150,
				align: "center",
				customRender: ({ text, record, index, column }) => {
					//未设置dataIndex，text和record返回值相同
					return dayjs(text).format("YYYY-MM-DD HH:mm:ss");
				}
			},
			{
				title: "签收状态",
				dataIndex: "receive_status",
				sorter: false,
				width: 100,
				align: "center",
				customRender: ({ text, record, index, column }) => {
					return text === 1 ? "待收料" : "已收料";
				}
			},
			{
				title: "操作",
				key: "operation",
				sorter: false,
				fixed: "right",
				width: 80,
				align: "center"
			}
		]
	}
})

const tableScroll = computed(() => ({
	x: document.documentElement.clientWidth - 650
}));
const doSearch = () => {
	current.value = 1;
	loading.value = true;
	initData();
};
const innerProjectOptions = computed(() => {
	let options = [];
	if (!projectOptions.value.length) return options;
	if (searchState.company_id) {
		options = projectOptions.value.filter((item) => {
			return item.parseIds.includes(searchState.company_id);
		})
	} else {
		options = projectOptions.value;
	}
	if (!options.filter(item => item.value === searchState.project_id).length) {
		searchState.project_id = null;
	}
	return options;
})

const changeflowStatus = e => {
	if (e && searchState) {
		searchState.ids = e.ids;
		if (searchState.ids) {
			initData();
		}
	}
};
const { data, loading, run, current, pageSize, total } = usePagination(async params => {
	const search = { };
	if (searchState.type === 0) {
		if (searchState.company_id) {
			if (!projectOptions.value.length) await getProjects();
			search.project_ids = projectOptions.value.filter((item) => {
				return item.parseIds.includes(searchState.company_id);
			}).map(item => item.value).join(',');
			if (!search.project_ids) {
				return [];
			}
		}
		return post("uselog", { 
			...params, 
			...searchState, 
			...search, 
			start_time: searchState.date_range && searchState.date_range[0],
			end_time: searchState.date_range && searchState.date_range[1], 
		})
	} else {
		return post("uselog/materials", { 
			...params, 
			...searchState,
			start_time: searchState.date_range && searchState.date_range[0],
			end_time: searchState.date_range && searchState.date_range[1], 
		})
	}
	
}, {
	defaultParams: [
		{
			page_size: 10
		}
	],
	pagination: {
		currentKey: "page",
		pageSizeKey: "page_size",
		totalKey: "total"
	}
});

// 导出
const handleExport = () => {
	post("uselog", {
		page_size: Infinity,
		submit: 'export',
		...searchState
	}).then(({ url }) => {
		if (url) window.location.href = url;
	})
}

const acceptSource = computed(() =>
	(data.value?.data || []).map(d => {
		if (d.children?.length === 0) delete d.children;
		//格式化接收人
		if (d.opr_type === 1) {
			if (d?.client?.name) {
				d.receiver = `${d?.client?.name}（${d?.supplier?.company_name}）`;
			} else {
				d.receiver = `${d?.receiver?.fullname}（${d?.supplier?.company_name}）`;
			}
		} else {
			d.receiver = d?.receiver?.fullname;
		}
		return d;
	})
);

const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value
}));

const initData = (pag, filters, sorter) => {
	pag = Object.assign(
		{
			current: current.value,
			pageSize: pageSize.value
		},
		pag || {}
	);
	filters = { ...filters, ...searchState };
	const query = {};
	if (pag?.pageSize) {
		query['page_size'] = pag?.pageSize;
	}
	if (pag?.current) {
		query['page'] = pag?.current;
	}
	router.replace({ query: {
		...query,
		...filters,
		// start_time: searchState.date_range && searchState.date_range[0],
		// end_time: searchState.date_range && searchState.date_range[1],
	}})
	run({
		page_size: pag?.pageSize,
		page: pag?.current,
		sort_field: sorter?.field,
		sort_order: sorter?.order,
		...filters
	});
};
if (query) {
	if (query.company_id) searchState.company_id = parseInt(query.company_id);
	if (query.project_id) searchState.project_id = parseInt(query.project_id);
	if (query.receiver_name) searchState.receiver_name = query.receiver_name;
	if (query.type) searchState.type = parseInt(query.type);
	const pag = {};
	if (query.page) {
		pag['current'] = parseInt(query.page);
	}
	if (query.pageSize) {
		pag['pageSize'] = parseInt(query.page_size);
	}
	initData(pag);
}

const showUselog = ({ id }) => {
	router.push(`uselog/info/${id}`);
};
const editUselog = ({ id }) => {
	router.push(`uselog/edit/${id}`);
};
const deleteUselog = id => {
	proxy.$confirm({
		title: "确认提示",
		content: `确定要删除${typeof id === "number" ? "当前" : "选中"}的申请记录吗？`,
		okText: "确认",
		cancelText: "取消",
		onOk() {
			post("uselog/delete", { id }).then(() => {
				proxy.$message.success("记录删除成功");
				initData();
			});
		}
	});
};
</script>
<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;
}
</style>